import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:lcapp/api/interface/user_api.dart';
import 'package:lcapp/api/request/response_data.dart';
import 'package:lcapp/basic/user_info.dart';
import 'package:lcapp/data/vip_type_data_entity.dart';
import 'package:lcapp/model/db/apple_pay_operate.dart';
import 'package:lcapp/model/event/event_bus.dart';
import 'package:lcapp/model/param/base_param.dart';
import 'package:lcapp/model/pay/in_app_pay.dart';
import 'package:lcapp/model/toast/toast.dart';
import 'package:lcapp/page/min/choose_payment_page.dart';

class MinOpenVipDialogPage extends StatefulWidget {
  const MinOpenVipDialogPage({Key? key}) : super(key: key);

  @override
  _MinOpenVipDialogPageState createState() => _MinOpenVipDialogPageState();
}

class _MinOpenVipDialogPageState extends State<MinOpenVipDialogPage> {

  late int vipType;
  List<VipTypeDataEntity> vips=[VipTypeDataEntity(),VipTypeDataEntity()];

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    refreshUserInfo(refreshBlock: (){setState(() {});});

    getVipList();
  }

  getVipList()async{
    ResponseData res = await UserAPI.getVipList();
    if(res.code==200){
      List arr = res.data??[];
      vips.clear();
      for (var element in arr) {
        VipTypeDataEntity entity = VipTypeDataEntity().fromJson(element);
        vips.add(entity);
      }
      if(mounted){setState(() {
        if(vips.isNotEmpty){
          vipType = vips[0].id!;
        }
      });}
    }
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      width: 1.sw,
      decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(20.w)
      ),
      padding: EdgeInsets.only(bottom: ScreenUtil().bottomBarHeight+20.w,top: 50.w),
      child: SingleChildScrollView(
        child: Container(
          padding: EdgeInsets.symmetric(horizontal:30.w,),
          child:Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Container(
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Container(
                      height: 1,
                      width: 100.w,
                      color: Color(0xffD8D8D8),
                    ),
                    Container(
                      height: 12.w,
                      width: 12.w,
                      decoration: BoxDecoration(
                          color: Color(0xffD8D8D8),
                        borderRadius: BorderRadius.circular(12.w)
                      ),
                    ),
                    Container(
                      margin: EdgeInsets.symmetric(horizontal: 40.w),
                      child: Text('开通VIP查看更多',style: TextStyle(
                          color: Colors.black,
                          fontSize: 36.sp,
                          fontWeight: FontWeight.bold
                      ),),
                    ),
                    Container(
                      height: 12.w,
                      width: 12.w,
                      decoration: BoxDecoration(
                          color: Color(0xffD8D8D8),
                          borderRadius: BorderRadius.circular(12.w)
                      ),
                    ),
                    Container(
                      height: 1,
                      width: 100.w,
                      color: Color(0xffD8D8D8),
                    ),
                  ],
                ),
                margin: EdgeInsets.only(bottom: 80.w),
              ),
              Row(
                children: [
                  GestureDetector(
                    onTap: (){
                      setState(() {
                        vipType=vips[0].id!;
                      });
                    },
                    child: Stack(
                      children: [
                        Container(
                          width: (1.sw-60.w-11.w)*0.5,
                          height: vipType==vips[0].id? 230.w:220.w,
                          decoration: BoxDecoration(
                              gradient: vipType==vips[0].id?LinearGradient(
                                  colors: [Color(0xffFFEBCE),Color(0xffFFEBCE)],
                                  begin: Alignment.topCenter,
                                  end: Alignment.bottomCenter
                              ):LinearGradient(
                                  colors: [Color(0xffF7F7F7),Color(0xffF7F7F7)],
                                  begin: Alignment.topCenter,
                                  end: Alignment.bottomCenter
                              ),
                              borderRadius: BorderRadius.circular(10.w),
                            border: Border.all(color: vipType==vips[0].id?Color(0x6f7B5228):Color(0x6fC4C4C4))
                          ),
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.start,
                            children: [
                              vipType==vips[0].id&&userInfo.inviter!=null&&userInfo.inviter!=userInfo.invite&&userInfo.invite!='0'?Row(
                                children: [
                                  Image.asset('assets/min/min_djq.png',width: 200.w,)
                                ],
                              ):Container(height: 30.w,),
                              Text('vip年卡(1年)',style: TextStyle(
                                  color:vipType==vips[0].id? Color(0xff7B5228):Color(0xff757575),
                                  fontWeight: FontWeight.w600,
                                  fontSize: 28.sp
                              ),),
                              SizedBox(height: 15.w,),
                              Text(BaseParam.isCheck?'购年卡':'￥${vips[0].priceCurrent}',style: TextStyle(
                                  color: vipType==vips[0].id?Color(0xff7B5228):Color(0xff757575),
                                  fontWeight: FontWeight.w600,
                                  fontSize: 40.sp
                              ),),
                              SizedBox(height: 15.w,),
                              Text(BaseParam.isCheck?'尊享年卡权益':'原价￥${vips[0].priceOriginal}',style: TextStyle(
                                  color:vipType==vips[0].id? Color(0xff7B5228):Color(0xff757575),
                                  fontWeight: FontWeight.w600,
                                  fontSize: 28.sp
                              ),),
                            ],
                          ),
                        ),
                      ],
                    ),
                  ),
                  SizedBox(width: 11.w,),
                  GestureDetector(
                    onTap: (){
                      setState(() {
                        vipType=vips[1].id!;
                      });
                    },
                    child: Stack(
                      children: [
                        Container(
                          width: (1.sw-60.w-11.w)*0.5,
                          height: vipType==vips[1].id? 230.w:220.w,
                          decoration: BoxDecoration(
                              gradient: vipType==vips[1].id?LinearGradient(
                                  colors: [Color(0xffFFEBCE),Color(0xffFFEBCE)],
                                  begin: Alignment.topCenter,
                                  end: Alignment.bottomCenter
                              ):LinearGradient(
                                  colors: [Color(0xffF7F7F7),Color(0xffF7F7F7)],
                                  begin: Alignment.topCenter,
                                  end: Alignment.bottomCenter
                              ),
                              borderRadius: BorderRadius.circular(10.w),
                              border: Border.all(color: vipType==vips[1].id?Color(0x6f7B5228):Color(0x6fC4C4C4))
                          ),
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.start,
                            children: [
                              vipType==vips[1].id&&userInfo.inviter!=null&&userInfo.inviter!=userInfo.invite&&userInfo.invite!='0'?Row(
                                children: [
                                  Image.asset('assets/min/min_djq.png',width: 200.w,)
                                ],
                              ):Container(height: 30.w,),
                              Text('vip年卡(2年)',style: TextStyle(
                                  color:vipType==vips[1].id? Color(0xff7B5228):Color(0xff757575),
                                  fontWeight: FontWeight.w600,
                                  fontSize: 28.sp
                              ),),
                              SizedBox(height: 15.w,),
                              Text(BaseParam.isCheck?'购年卡':'￥${vips[1].priceCurrent}',style: TextStyle(
                                  color: vipType==vips[1].id?Color(0xff7B5228):Color(0xff757575),
                                  fontWeight: FontWeight.w600,
                                  fontSize: 40.sp
                              ),),
                              SizedBox(height: 15.w,),
                              Text(BaseParam.isCheck?'尊享年卡权益':'原价￥${vips[1].priceOriginal}',style: TextStyle(
                                  color:vipType==vips[1].id? Color(0xff7B5228):Color(0xff757575),
                                  fontWeight: FontWeight.w600,
                                  fontSize: 28.sp
                              ),),
                            ],
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
                crossAxisAlignment: CrossAxisAlignment.end,
              ),
              GestureDetector(
                onTap: ()async{
                  if(userInfo.vip==1){
                    showToast('当前已是会员身份');
                    eventBus.fire(PayState(0, PayType.PayType_ALI));
                    return;
                  }
                  double? money;
                  if(vipType==vips[0].id){
                    money = vips[0].priceCurrent;
                    if(userInfo.inviter!=null&&userInfo.inviter!=userInfo.invite&&userInfo.invite!='0'){
                      money = vips[0].priceReduced;
                    }
                  }else{
                    money=vips[1].priceCurrent;
                    if(userInfo.inviter!=null&&userInfo.inviter!=userInfo.invite&&userInfo.invite!='0'){
                      money = vips[1].priceReduced;
                    }
                  }
                  if(BaseParam.isCheck){
                    showLoading();
                    ResponseData res = await UserAPI.applePay(vipType);
                    hideLoading();
                    if(res.code==200){
                      Map<String, dynamic> map = {
                        'orderId': res.data['orderId'],
                        'productId': res.data['sku'],
                        'createTime': DateTime.now().millisecondsSinceEpoch
                      };
                      ApplePayDBOperate.insertPayHistoryInfo(map);
                      InAppPay.pay(
                          PayType.PayType_APPLE,sku: res.data['sku'],orderId: res.data['orderId']);
                    }
                    return;
                  }
                  SmartDialog.show(
                    alignment: Alignment.bottomCenter,
                    clickMaskDismiss: true,
                    maskColor: Color.fromRGBO(0, 0, 0, 0.5), builder: (BuildContext context) {
                      return ChoosePaymentPage(total: money??0,id: vipType,);
                  },
                  );
                },
                child: Container(
                  margin: EdgeInsets.only(top: 50.w),
                  child: Container(
                    height: 90.w,
                    width: 1.sw-60.w,
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                        gradient: const LinearGradient(
                            colors: [Color(0xffEDD0A8),Color(0xffF1BF83)],
                            begin: Alignment.centerLeft,
                            end: Alignment.centerRight
                        ),
                        borderRadius: BorderRadius.circular(80.w)
                    ),
                    child: Text('确认开通VIP',style: TextStyle(
                        color: Color(0xff7D532A),
                        fontWeight: FontWeight.w600,
                        fontSize: 32.sp
                    ),),
                  ),
                ),
              ),
              GestureDetector(
                onTap: (){
                  SmartDialog.dismiss();
                },
                child: Container(
                  margin: EdgeInsets.only(top: 40.w),
                  child: Text(
                    '我再想想',
                    style: TextStyle(
                        decoration: TextDecoration.underline,
                        fontSize: 30.sp,
                        color: Color(0xffA8A8A8)
                    ),
                  ),
                ),
              )
            ],
          ),
        ),
      ),
    );
  }
}
